package com.peanut.service.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;

import org.apache.commons.lang.BooleanUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import com.peanut.model.Role;
import com.peanut.persistence.RoleMapper;
import com.peanut.persistence.UserMapper;

/**
 * 
 * @author Johan.Chenjh
 *
 * 2011-3-20
 */
public class SecurityUserDetailServiceImpl implements UserDetailsService {
	protected final transient Logger log = Logger.getLogger(getClass());
	
	@Autowired
	public UserMapper userMapper;
	
	@Autowired
	public RoleMapper roleMapper;

	public UserDetails loadUserByUsername(String username)
			throws UsernameNotFoundException, DataAccessException {
		//Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
		//GrantedAuthorityImpl auth1 = new GrantedAuthorityImpl("ROLE_ADMIN");
		//auths.add(auth1);

		// User(String username, String password, boolean enabled, boolean
		// accountNonExpired,
		// boolean credentialsNonExpired, boolean accountNonLocked,
		// Collection<GrantedAuthority> authorities) {
		//User springUser = null;
		com.peanut.model.User user = null;
		if ("superadmin".equals(username)) {
			Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			GrantedAuthorityImpl auth = new GrantedAuthorityImpl("ROLE_SUPERADMIN");
			auths.add(auth);
			user = new com.peanut.model.User(username, "1", true, true, true, true, auths);
		} else {
			//user = userMapper.queryByAccount(username);
			HashMap<String, String> userMap = userMapper.queryByUsername(username);
			user = recieveUser(userMap);
			if (user == null) {
				throw new AuthenticationServiceException("用户名或者密码错误！"); 
			}
//			if (user != null) {
//				List<Role> roleList = roleMapper.queryRolesByAccount(username);
//				user.setRoles(roleList);
//			}
//			if (user != null) {
//				if (user.getRoles() != null) {
//					for (Role role : user.getRoles()) {
//						GrantedAuthorityImpl auth = new GrantedAuthorityImpl(role.getName());
//						auths.add(auth);
//					}
//				}
//				springUser = new User(username, user.getPassword(), BooleanUtils.toBoolean(user.getEnabled()), 
//						BooleanUtils.toBoolean(user.getAccountNonExpired()), BooleanUtils.toBoolean(user.getCredentialsNonExpired()), 
//						BooleanUtils.toBoolean(user.getAccountNonLocked()), auths);
//			}
		}
		return user;
	}

	private com.peanut.model.User recieveUser(HashMap<String, String> userMap) {
		com.peanut.model.User user = null;
		if (userMap != null) {
			Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			List<Role> roleList = roleMapper.queryRolesByAccount(userMap.get("usercode").toString());
			if (roleList != null) {
				for (Role role : roleList) {
					GrantedAuthorityImpl auth = new GrantedAuthorityImpl(role.getName());
					auths.add(auth);
				}
			}
			user = new com.peanut.model.User(userMap.get("usercode").trim(), userMap.get("password").trim(), 
					BooleanUtils.toBoolean(Integer.parseInt(String.valueOf(userMap.get("enabled")))), 
					BooleanUtils.toBoolean(Integer.parseInt(String.valueOf(userMap.get("accountnonexpired")))), 
					BooleanUtils.toBoolean(Integer.parseInt(String.valueOf(userMap.get("credentialsnonexpired")))), 
					BooleanUtils.toBoolean(Integer.parseInt(String.valueOf(userMap.get("accountnonlocked")))), 
					auths);
			user.setUsername(userMap.get("username").trim());
			user.setCompanyCode(userMap.get("comcode").trim());
			user.setCompanyName(userMap.get("comcname").trim());
			user.setFlag(userMap.get("flag").trim());
			user.setVersion(Integer.parseInt(String.valueOf(userMap.get("version"))));
			user.setUserType(userMap.get("user_type"));
			user.setRoles(roleList);
		}
		return user;
	}
	
	@SuppressWarnings("unused")
	private com.peanut.model.User recieveUser2(String username) {
		com.peanut.model.User user = userMapper.queryByAccount(username);;
		if (user != null) {
			Collection<GrantedAuthority> auths = new ArrayList<GrantedAuthority>();
			List<Role> roleList = roleMapper.queryRolesByAccount(user.getUserCode());
			if (roleList != null) {
				for (Role role : roleList) {
					GrantedAuthorityImpl auth = new GrantedAuthorityImpl(role.getName());
					auths.add(auth);
				}
				user.setRoles(roleList);
			}
			user = new com.peanut.model.User(user.getUserCode(), user.getPassword(), 
					user.isEnabled(), 
					user.isAccountNonExpired(), 
					user.isCredentialsNonExpired(), 
					user.isAccountNonLocked(), 
					auths);
		}
		return user;
	}

}
